package com.sxbbc.api.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxbbc.common.basics.service.config.Config;
import com.sxbbc.common.basics.utils.statics.EnumUtils;
import com.sxbbc.common.core.dto.jz.*;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.mapper.jz.*;
import com.sxbbc.common.core.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.api.service.IBusinessService;
import com.sxbbc.common.basics.enums.ServiceEnums;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.encrypts.pwd.Encode;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.service.system.pay.PayService;
import com.sxbbc.common.core.utils.BasePage;

/**
 * 店铺数据 业务实现类
 *
 * @author xiaoky
 * @date 2019-05-27
 */
@Service
public class BusinessService extends ServiceImpl<BBusinessMapper, BBusiness> implements IBusinessService {
    @Autowired
    private ICPayLogService icPayLogService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private IBusinessService iBusinessService;
    @Autowired
    private IAccountChangeService accountChangeService;
    @Autowired
    private OrderMainMapper orderMainMapper;
    @Autowired
    private ISysCashRuleService iSysCashRuleService;
    @Autowired
    private BankDetailMapper bankDetailMapper;
    @Autowired
    private SysCashRuleMapper sysCashRuleMapper;
    @Autowired
    private BBusinessMapper businessMapper;
    @Autowired
    private BOfflineEvaluateMapper offlineEvaluateMapper;
    @Autowired
    private IBankDetailService iBankDetailService;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CAccountMapper cAccountMapper;
    @Autowired
    private BOfflineMapper offlineMapper;
    @Autowired
    private CCustomerMapper customerMapper;
    @Autowired
    private CCollectBusMapper cCollectBusMapper;
    @Autowired
    private ProcMainMapper procMainMapper;
    @Autowired
    private BAccountMapper bAccountMapper;
    @Autowired
    private IBMoneyDetailService bMoneyDetailService;
    @Autowired
    private PayService payService;
    @Autowired
    private IBFreezeMoneyDetailService bFreezeMoneyDetailService;
    @Autowired
    private ICCustomerService icCustomerService;
    @Autowired
    private ISysCashDetailsService iSysCashDetailsService;
    @Autowired
    private ProcEvaluateMapper procEvaluateMapper;
    @Autowired
    private IInfoParamService iInfoParamService;
    @Autowired
    private ICCustomerAuthenService customerAuthenService;
    @Autowired
    private BOfflineMapper bOfflineMapper;
    @Autowired
    private IIndustryService iIndustryService;
    @Autowired
    private IIndustryDetailService iIndustryDetailService;
    @Autowired
    private BMoneyDetailMapper bMoneyDetailMapper;

    /**
     * 处理店铺图片
     *
     * @param coverUrl
     * @return
     */
    private List<String> handleBusCoverUrl(String coverUrl) {
        // 处理店铺门头照
        List<String> coverUrlList = new ArrayList<>();
        if (!StringUtils.isEmpty(coverUrl)) {
            JSONArray jsonArray = JSON.parseArray(coverUrl);
            for (Object object : jsonArray) {
                String str = "";
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object);
                str = (String) jsonObject.get("url");
                coverUrlList.add(str);
            }
        }
        return coverUrlList;
    }

    @Override
    public IPage<NearBusinessVo> queryNearBusiness(BasePage<BBusiness> page, BBusiness business) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();

        if (StringUtils.isNotBlank(business.getCityName())) {
            Map<String, String> amap = calcuUtils.getLatAndLonByAmap(Config.properties.getAmapKey(), business.getCityName());
            if (amap.size() == 2) {
                business.setLonVal(amap.get("lon"));
                business.setLatVal(amap.get("lat"));
            }
        }

        IPage<NearBusinessVo> pageInfo = businessMapper.queryNearBusiness(page, business);
        if (pageInfo.getSize() > 0) {
            for (NearBusinessVo record : pageInfo.getRecords()) {
                // 地址详情处理(加上省市县)
                String proName = addressMapper.selectAddressNameById(record.getProId());
                String cityName = addressMapper.selectAddressNameById(record.getCityId());
                String areaName = addressMapper.selectAddressNameById(record.getAreaId());
                record.setAddressDetail(proName + " " + cityName + " " + areaName + " " + record.getAddressDetail());
                record.setBusinessTypeName(EnumUtils.getEnum(BusinessTypeEnums.class, EnumUtils.GET_ID, record.getBType()).getName());
                //行业名
                Industry industry = iIndustryService.getById(record.getIndustryId());
                if (industry != null) {
                    record.setIndustryName(industry.getName());
                }
                //门头照
                record.setCoverUrlList(handleBusCoverUrl(record.getCoverUrl()));
                record.setLogo(record.getHeadUrl());
            }
        }
        return pageInfo;
    }

    @Override
    public NearBusinessDetailVo getBusinessDetail(Integer bid) {
        BBusiness business = businessMapper.selectById(bid);
        if (business == null) {
            throw new ThrowJsonException("查询店铺详情异常");
        }
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        // 审核是否通过
        if (!calcuUtils.isEquals(business.getOfflineStatus(), StaticUtils.STATUS_SUCCESS)
                && !calcuUtils.isEquals(business.getStatus(), StaticUtils.STATUS_SUCCESS)) {
            throw new ThrowJsonException("商家尚未审核通过");
        }
        if (!calcuUtils.isEquals(business.getOnOff(), BusinessScopeEnums.OFFLINE.getId())
                && !calcuUtils.isEquals(business.getOnOff(), BusinessScopeEnums.ONLINE.getId())) {
            throw new ThrowJsonException("商家类型有误");
        }
        NearBusinessDetailVo vo = new NearBusinessDetailVo();
        BeanUtils.copyProperties(business, vo);
        vo.setCoverUrlList(handleBusCoverUrl(vo.getCoverUrl()));
        // 地址详情处理(加上省市县)
        String proName = addressMapper.selectAddressNameById(business.getProId());
        String cityName = addressMapper.selectAddressNameById(business.getCityId());
        String areaName = addressMapper.selectAddressNameById(business.getAreaId());
        vo.setAddressDetail(proName + " " + cityName + " " + areaName + " " + vo.getAddressDetail());
        vo.setBusinessTypeName(EnumUtils.getEnum(BusinessTypeEnums.class, EnumUtils.GET_ID, vo.getBType()).getName());
        return vo;
    }

    @Override
    public Map<String, Object> getBuyMsg(Integer bid, Integer cid, Integer scan) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        Map<String, Object> map = new HashMap<String, Object>();
        BBusiness business = businessMapper.selectById(bid);
        if (business == null) {
            throw new ThrowJsonException("商家不存在");
        }
        map.put("bNickName", business.getNickName());
        CAccount account = cAccountMapper.getByCid(cid);
        if (account == null) {
            throw new ThrowJsonException("用户资金账户信息获取失败，请检查网络");
        }
        map.put("money", account.getMoney());
        map.put("bid", bid);
        // 如果是扫码进入
        if (calcuUtils.isEquals(StaticUtils.STATUS_YES, scan)) {
            BAccount bAccount = bAccountMapper.getByBid(bid);
            if (bAccount == null) {
                throw new ThrowJsonException("商家账户有误");
            }
            map.put("payMoney", bAccount.getQrMoney());
        }
        return map;
    }

    @Override
    public RestResponse handleOfflineEvaluate(BOfflineEvaluate evaluate) {
        BOffline offline = offlineMapper.getByPayCode(evaluate.getPayCode());
        if (offline == null) {
            return GetRest.getFail("交易不存在");
        }
        CCustomer customer = customerMapper.selectById(evaluate.getCid());
        if (customer == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        BBusiness business = businessMapper.selectById(evaluate.getBid());
        if (business == null) {
            return GetRest.getFail("异常评论");
        }
        if (evaluate.getScore() == null) {
            return GetRest.getFail("给个评分吧");
        }
        if (StringUtils.isEmpty(evaluate.getContent())) {
            return GetRest.getFail("评论一下吧");
        }
        int result = offlineEvaluateMapper.insert(evaluate);
        if (result < 1) {
            return GetRest.getFail("评论失败");
        }
        return GetRest.getSuccess("评论成功");
    }

    @Override
    public Map<String, Object> getNearBuyAfter(Integer cid, String payCode) {
        BOffline offline = offlineMapper.getByPayCode(payCode);
        if (offline == null) {
            throw new ThrowJsonException("交易不存在");
        }
        if (!CalcuUtils.getInstance().isEquals(cid, offline.getCid())) {
            throw new ThrowJsonException("交易错误");
        }
        // 店铺名(即页面上对应收款方)
        String bNickName = "";
        BBusiness business = businessMapper.selectById(offline.getBid());
        if (business != null) {
            bNickName = business.getNickName();
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("bid", business.getId());
        // 支付状态
        map.put("status", offline.getStatus());
        // 支付方式
        map.put("payTypeName", PayTypeEnums.getName(offline.getPayType()));
        // 支付金额
        map.put("money", offline.getMoney());
        // 获得积分
        map.put("point", offline.getPoint());
        // 收款方
        map.put("bNickName", bNickName);
        // 交易单号
        map.put("payCode", payCode);
        return map;
    }

    @Override
    public RestResponse handleOfflineBuy(BOffline offline, String payWord, Integer payChannel) {
        CCustomer customer = customerMapper.selectById(offline.getCid());
        if (customer == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        //用户账户冻结不能买单
        String desc = icCustomerService.checkFrezeeCustomer(customer.getStatus(), UserFreezeEnums.CUSTOMER_OFFLINE_BUY.getId(), null);
        if (desc.length() > 0) {
            return GetRest.getFail(desc);
        }

        BBusiness business = businessMapper.selectById(offline.getBid());
        if (business == null) {
            return GetRest.getFail("获取店铺信息失败");
        }

        if (!PayTypeEnums.isPay(offline.getPayType())) {
            return GetRest.getFail("支付方式不存在");
        }

        if (offline.getMoney() == null) {
            return GetRest.getFail("请输入买单金额");
        }
        if (offline.getMoney().compareTo(BigDecimal.ZERO) <= 0) {
            return GetRest.getFail("买单金额错误");
        }

        if (CalcuUtils.getInstance().isEquals(offline.getPayType(), PayTypeEnums.PAY_MONEY.getId())) {
            if (!CalcuUtils.getInstance().isEquals(customer.getAuthen(), StaticUtils.STATUS_YES)) {
                return GetRest.getFail("请先进行身份认证", null, "2");
            }
            // 判断是否余额支付——余额支付需要校验密码
            if (StringUtils.isEmpty(payWord)) {
                return GetRest.getFail("请输入支付密码");
            }
            String encryPayword = Encode.md5Encode(payWord);
            if (!encryPayword.equals(customer.getPayWord())) {
                if (StringUtils.isBlank(customer.getPayWord())) {
                    return GetRest.getFail("您还未设置支付密码", null, "1");
                } else {
                    return GetRest.getFail("支付密码不正确");
                }
            }
        }

        //计算赠送创业分
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        BigDecimal point = calcuUtils.mul(business.getScale(), offline.getMoney(), 2);

        // 生成交易单号
        String payCode = CalcuUtils.getInstance().getOrderCode("OL");
        offline.setPayCode(payCode);
        offline.setPoint(point);
        int i = offlineMapper.insert(offline);
        if (i < 1) {
            return GetRest.getFail("买单失败", "", payCode);
        }

        // 生成支付记录
        CPayLog log = new CPayLog();
        log.setCid(offline.getCid());
        log.setPayCode(payCode);
        log.setPayMoney(offline.getMoney());
        log.setServiceType(ServiceEnums.OFFLINE_BUY.getId());
        log.setPayChannel(payChannel);
        log.setPayType(offline.getPayType());
        log.setPoint(point);
        if (CalcuUtils.getInstance().isEquals(PayChannlEnums.WX_PUBLIC.getId(), payChannel)) {
            log.setOpenId(customer.getOpenidWx());
        } else {
            if (CalcuUtils.getInstance().isEquals(PayChannlEnums.WX_PROGRAM.getId(), payChannel)) {
                log.setOpenId(customer.getOpenidProgram());
            }
        }
        boolean flag = icPayLogService.save(log);
        if (!flag) {
            throw new ThrowJsonException("生成支付记录失败");
        }

        //支付记录存在之后开始处理订单签名
        return payService.handleSign(log);
    }

    @Override
    public IPage<BMoneyDetail> queryBusinessMoneyDetail(Integer cid, BasePage<BMoneyDetail> page) {
        // 通过cid查询对应店铺
        // 店铺信息
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business == null) {
            return page;
        } else {
            BMoneyDetail moneyDetail = new BMoneyDetail();
            moneyDetail.setBid(business.getId());
            IPage<BMoneyDetail> pageInfo = bMoneyDetailService.queryBusinessMoneyDetail(page, moneyDetail);
            return pageInfo;
        }
    }

    @Override
    public RestResponse handleBusinessCash(Integer cid, String payWord, SysCashDetails detail) {
        CCustomer customer = customerMapper.selectById(cid);
        if (customer == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        if (CalcuUtils.getInstance().isEquals(StaticUtils.STATUS_NO, customer.getStatus())) {
            String desc = icCustomerService.checkFrezeeCustomer(UserFreezeEnums.BUSINESS_CASH.getId(), null);
            if (desc.length() > 0) {
                return GetRest.getFail(desc);
            }

        }
        // 判断是否余额支付——余额支付需要校验密码
        if (StringUtils.isEmpty(payWord)) {
            return GetRest.getFail("请输入支付密码");
        }
        String encryPayword = Encode.md5Encode(payWord);
        if (!encryPayword.equals(customer.getPayWord())) {
            if (StringUtils.isBlank(customer.getPayWord())) {
                return GetRest.getFail("您还未设置支付密码", null, "1");
            } else {
                return GetRest.getFail("支付密码不正确");
            }
        }

        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business == null) {
            return GetRest.getFail("提现失败");
        } else {
            detail.setTargetId(business.getId());
            detail.setType(CashTypeEnums.BUSINESS.getId());
            RestResponse result = iSysCashDetailsService.handleCashApply(detail);
            return result;
        }
    }

    @Override
    public BusinessInfoVo queryBusinessLinkMsg(Integer bid) {
        BusinessInfoVo vo = new BusinessInfoVo();
        BBusiness business = businessMapper.selectById(bid);
        if (business == null) {
            return vo;
        }
        if (CalcuUtils.getInstance().isEquals(business.getBType(), BusinessTypeEnums.OWN_BUSINESS.getId())) {
            vo.setbTypeName(BusinessTypeEnums.OWN_BUSINESS.getName());
            vo.setLinkPhone(business.getPhone());
        }
        BeanUtils.copyProperties(business, vo);
        return vo;
    }

    @Override
    public IPage<BFreezeMoneyDetail> queryBusinessFreezeMoneyDetail(Integer cid, IPage<BFreezeMoneyDetail> page) {
        // 通过cid查询对应店铺
        // 店铺信息
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business != null) {
            BFreezeMoneyDetail detail = new BFreezeMoneyDetail();
            detail.setBid(business.getId());
            bFreezeMoneyDetailService.queryBusinessFreezeMoneyDetail(page, detail);
        }
        return page;
    }

    @Override
    public RestResponse selectMerchantCenterData(Integer cid) {
        // 店铺信息
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business == null) {
            return GetRest.getFail("店铺信息有误");
        }
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        if (!calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getStatus())
                && !calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getOfflineStatus())) {
            return GetRest.getFail("店铺未通过审核");
        }
        if (StringUtils.isNotBlank(business.getWorkTime()) && business.getIswhether() == null) {
            String[] split = business.getWorkTime().split("~");
            if (split.length == 2) {
                LocalDateTime now = LocalDateTime.now();
                int nowHour = now.getHour();
                int nowSecond = now.getSecond();
                String[] startTime = split[0].split(":");
                String[] endTime = split[1].split(":");
                if (startTime[0].compareTo(String.valueOf(nowHour)) < 0
                        && startTime[1].compareTo(String.valueOf(nowSecond)) < 0
                        && endTime[0].compareTo(String.valueOf(nowHour)) > 0
                        && endTime[1].compareTo(String.valueOf(nowSecond)) > 0) {
                    business.setIswhether(StaticUtils.STATUS_YES);
                } else {
                    business.setIswhether(StaticUtils.STATUS_NO);
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("business", business);
        // 查询今日营业总额
        BigDecimal todayEarnings = bMoneyDetailMapper.getMerchantCenterTurnover(business.getId(), StaticUtils.DATE_TYPE_DAY);
        map.put("todayEarnings", todayEarnings);
        // 查询本月营业总额
        BigDecimal revenueThisMonth = bMoneyDetailMapper.getMerchantCenterTurnover(business.getId(), StaticUtils.DATE_TYPE_MONTH);
        map.put("revenueThisMonth", revenueThisMonth);
        // 店铺钱包
        BAccount bAccount = bAccountMapper.getByBid(business.getId());
        map.put("wallet", bAccount.getMoney());
        return GetRest.getSuccess("操作成功", map);
    }

    @Override
    public RestResponse editOperatingStatus(Integer cid, Integer status, String workTime) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        if (!calcuUtils.isEquals(StaticUtils.STATUS_YES, status)
                && !calcuUtils.isEquals(StaticUtils.STATUS_NO, status)) {
            return GetRest.getFail("参数错误");
        }
        // 店铺信息
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business == null) {
            return GetRest.getFail("店铺信息有误");
        }

        if (!calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getStatus())
                && !calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getOfflineStatus())) {
            return GetRest.getFail("店铺未通过审核");
        }
        if (status != null) {
            business.setIswhether(status);
        }
        if (StringUtils.isNotBlank(workTime)) {
            business.setWorkTime(workTime);
        }
        businessMapper.updateById(business);
        return GetRest.getSuccess("操作成功");
    }

    @Override
    public RestResponse queryTurnoverDetailsList(Integer cid, Integer dateType) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        // 店铺信息
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business == null) {
            return GetRest.getFail("店铺信息有误");
        }
        if (!calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getStatus())
                && !calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getOfflineStatus())) {
            return GetRest.getFail("店铺未通过审核");
        }
        if (dateType == null) {
            return GetRest.getFail("参数不能为空");
        }
        if (!calcuUtils.isEquals(StaticUtils.DATE_TYPE_DAY, dateType) && !calcuUtils.isEquals(StaticUtils.DATE_TYPE_MONTH, dateType)) {
            return GetRest.getFail("参数错误");
        }

        Map<String, Object> map = new HashMap<>();
        // 根据店铺id查询店铺营业额
        BigDecimal turnover = bMoneyDetailMapper.getMerchantCenterTurnover(business.getId(), dateType);
        map.put("turnover", turnover);
        // 查询店铺营业额明细记录列表
        List<BMoneyDetail> turnoverDetailsList = bMoneyDetailMapper.getTurnoverTodayList(business.getId(), dateType);
        if (turnoverDetailsList != null) {
            for (BMoneyDetail bMoneyDetails : turnoverDetailsList) {
                bMoneyDetails.setTypeName(HandleTypeEnums.getName(bMoneyDetails.getTypeId()));
            }
        }
        map.put("turnoverDetailsList", turnoverDetailsList);
        return GetRest.getSuccess("操作成功", map);
    }

    @Override
    public RestResponse queryWalletDetailsList(Integer cid, BasePage<BMoneyDetail> page) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        // 店铺信息
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business == null) {
            return GetRest.getFail("店铺信息有误");
        }
        if (!calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getStatus())
                && !calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getOfflineStatus())) {
            return GetRest.getFail("店铺未通过审核");
        }
        Map<String, Object> map = new HashMap<>();
        // 根据店铺id查询店铺账户信息
        BAccount bAccount = bAccountMapper.getByBid(business.getId());
        map.put("money", bAccount.getMoney());
        // 查询店铺钱包明细列表
        List<BMoneyDetail> bMoneyDetailsList = bMoneyDetailMapper.getStoreWalletDetailsList(page, business.getId());
        map.put("bMoneyDetailsList", bMoneyDetailsList);
        if (bMoneyDetailsList != null) {
            for (BMoneyDetail bMoneyDetails : bMoneyDetailsList) {
                bMoneyDetails.setTypeName(HandleTypeEnums.getName(bMoneyDetails.getTypeId()));
            }
        }
        return GetRest.getSuccess("操作成功", map);
    }

    @Override
    public RestResponse merchantCashWithdrawalPage(Integer cid) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        // 店铺信息
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business == null) {
            return GetRest.getFail("店铺信息有误");
        }
        if (!calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getStatus())
                && !calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getOfflineStatus())) {
            return GetRest.getFail("店铺未通过审核");
        }
        CashVo cashVo = new CashVo();
        //查询余额
        BAccount bAccount = bAccountMapper.getByBid(business.getId());
        cashVo.setSummoney(bAccount.getMoney());
        //查询银行卡
        BankDetail bank = new BankDetail();
        bank.setTargetId(business.getId());
        List<BankDetail> bankList = iBankDetailService.queryBankDetailList(business.getId(), CashTypeEnums.BUSINESS.getId());
        bankList.forEach(x -> x.setLastCode(x.getBankCard().substring(x.getBankCard().length() - 4, x.getBankCard().length())));
        //查询提现规则
        QueryWrapper<SysCashRule> wrapper = new QueryWrapper<>();
        wrapper.eq("role_type", CashTypeEnums.BUSINESS.getId());
        SysCashRule sysCashRule = iSysCashRuleService.getOne(wrapper);
        cashVo.setBankList(bankList);
        cashVo.setRule(sysCashRule);
        cashVo.setScale(calcuUtils.mul(sysCashRule.getScale(), BigDecimal.valueOf(100), 2).stripTrailingZeros().toBigInteger());
        return GetRest.getSuccess("", cashVo);
    }

    @Override
    public RestResponse offlineOrderInfo(Integer cid, String verifyCode) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        // 店铺信息
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business == null) {
            return GetRest.getFail("店铺信息有误");
        }
        if (!calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getStatus())
                && !calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getOfflineStatus())) {
            return GetRest.getFail("店铺未通过审核");
        }
        OfflineOrderOutVo vo = orderMainMapper.getVerifyCode(verifyCode);
        if (null == vo) {
            return GetRest.getFail("请输入正确的核销码");
        }
        if (CalcuUtils.getInstance().isEquals(business.getId(), vo.getBid())) {
            List<OrderDetail> cOrderDetails = orderDetailMapper.getListOrderDetails(vo.getOrderCode());
            vo.setOrderDetails(cOrderDetails);
            BigDecimal totalMoney = BigDecimal.ZERO;
            for (OrderDetail cOrderDetail : cOrderDetails) {
                totalMoney = calcuUtils.add(cOrderDetail.getGoodMoney(), totalMoney, 2);
            }
            vo.setTotalMoney(totalMoney);
            return GetRest.getSuccess("", vo);
        } else {
            return GetRest.getFail("你不是该订单的商家,无法核销");
        }
    }

    @Override
    public RestResponse orderVerify(Integer cid, String verifyCode) {
        CalcuUtils calcuUtils = CalcuUtils.getInstance();
        // 店铺信息
        QueryWrapper<BBusiness> queryWrapper = new QueryWrapper<BBusiness>();
        queryWrapper.eq("cid", cid);
        BBusiness business = businessMapper.selectOne(queryWrapper);
        if (business == null) {
            return GetRest.getFail("店铺信息有误");
        }
        if (!calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getStatus())
                && !calcuUtils.isEquals(StaticUtils.STATUS_SUCCESS, business.getOfflineStatus())) {
            return GetRest.getFail("店铺未通过审核");
        }
        OfflineOrderOutVo vo = orderMainMapper.getVerifyCode(verifyCode);
        if (null == vo) {
            return GetRest.getFail("请输入正确的核销码");
        }

        if (!calcuUtils.isEquals(vo.getOrderStatus(), OfflineOrderStatusEnums.WAIT_USED.getId())) {
            return GetRest.getFail("该订单状态不能核销");
        }

        //判断店铺id和核销码是否正确。正确给与核销
        if (calcuUtils.isEquals(vo.getBid(), business.getId()) && vo.getOrderCode().equals(verifyCode)) {
            OrderMain main = new OrderMain();
            main.setId(vo.getId());
            main.setOrderStatus(OfflineOrderStatusEnums.COMPLETE.getId());
            main.setOverTime(new Date());
            int i = orderMainMapper.updateById(main);
            if (i < 1) {
                return GetRest.getFail("核销失败，请重新在试");
            }

            //解冻用户、商家、代理对应的冻结余额
            accountChangeService.handleFreezeCustomerMoney(new FreezeDTO(FreezeStatusEnums.SEND.getId(), vo.getPayCode(), 1));
            accountChangeService.handleFreezeBusinessMoney(new FreezeDTO(FreezeStatusEnums.SEND.getId(), vo.getPayCode(), 1));
            accountChangeService.handleFreezeAgentMoney(new FreezeDTO(FreezeStatusEnums.SEND.getId(), vo.getPayCode(), 1));

            return GetRest.getSuccess("操作成功");
        }
        return GetRest.getFail("你不是该订单商家，无法核销");
    }

    @Override
    public RestResponse cashApply(SysCashDetails cashDetails, String payWord) {
        CCustomer customer = icCustomerService.getById(cashDetails.getTargetId());

        if (CalcuUtils.getInstance().isEquals(customer.getStatus(), StaticUtils.STATUS_NO)) {
            icCustomerService.checkFrezeeCustomer(UserFreezeEnums.CUSTOMER_CASH.getId(), null);
        }

        if (!CalcuUtils.getInstance().isEquals(customer.getAuthen(), StaticUtils.STATUS_YES)) {
            return GetRest.getFail("请先进行身份认证", null, "2");
        } else {
            //实名认证后需要判断该用户是否绑定银行卡
            QueryWrapper<CCustomerAuthen> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("cid", cashDetails.getTargetId());
            CCustomerAuthen authen = customerAuthenService.getOne(queryWrapper);
            if (authen == null) {
                return GetRest.getFail("请求错误，错误代码0000");
            } else if (StringUtils.isBlank(authen.getBankCard())) {
                //验证银行卡是否绑定
                int count = bankDetailMapper.countBankDetailByTargetId(cashDetails.getTargetId());
                if (count == 0) {
                    return GetRest.getFail("请先绑定银行卡");
                }
            }
        }

        // 校验密码
        if (StringUtils.isEmpty(payWord)) {
            return GetRest.getFail("请输入支付密码");
        }
        String encryPayword = Encode.md5Encode(payWord);
        if (!encryPayword.equals(customer.getPayWord())) {
            if (StringUtils.isBlank(customer.getPayWord())) {
                return GetRest.getFail("您还未设置支付密码", null, "1");
            } else {
                return GetRest.getFail("支付密码不正确");
            }
        }
        BBusiness business = iBusinessService.getOne(new QueryWrapper<BBusiness>().eq("cid", customer.getId()));
        cashDetails.setTargetId(business.getId());
        cashDetails.setType(CashTypeEnums.BUSINESS.getId());
        return iSysCashDetailsService.handleCashApply(cashDetails);
    }
}
